#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
查看数据库表结构
"""

import pymysql
import configparser
import os

def main():
    # 加载配置
    config = configparser.ConfigParser()
    config_path = 'config.ini'
    config.read(config_path, encoding='utf-8')

    db_config = dict(config['database'])
    for key, value in db_config.items():
        db_config[key] = value.strip('"\'').rstrip(',')

    print(f"数据库配置: host={db_config['host']}, port={db_config['port']}, user={db_config['user']}, db={db_config['db']}")

    # 连接数据库
    connection = pymysql.connect(
        host=db_config['host'],
        port=int(db_config['port']),
        user=db_config['user'],
        password=db_config['password'],
        db=db_config['db'],
        charset='utf8mb4',
        cursorclass=pymysql.cursors.DictCursor
    )

    try:
        with connection.cursor() as cursor:
            # 查看device_data_summary表结构
            cursor.execute('DESCRIBE device_data_summary')
            result = cursor.fetchall()
            print('\ndevice_data_summary表结构:')
            for field in result:
                print(f"  {field['Field']}: {field['Type']}")

        with connection.cursor() as cursor:
            # 查看ems_realtime_data表结构
            cursor.execute('DESCRIBE ems_realtime_data')
            result = cursor.fetchall()
            print('\nems_realtime_data表结构:')
            for field in result:
                print(f"  {field['Field']}: {field['Type']}")

        # 查看一些实际数据
        print('\n=== 查看device_data_summary中的时间数据 ===')
        with connection.cursor() as cursor:
            cursor.execute('SELECT record_time, timestamp FROM device_data_summary ORDER BY record_time DESC LIMIT 3')
            results = cursor.fetchall()
            for row in results:
                print(f"record_time: {row['record_time']}, timestamp: {row['timestamp']}")

        print('\n=== 查看ems_realtime_data中的时间数据 ===')
        with connection.cursor() as cursor:
            cursor.execute('SELECT timestamp, netherlands_timestamp FROM ems_realtime_data ORDER BY timestamp DESC LIMIT 3')
            results = cursor.fetchall()
            for row in results:
                print(f"timestamp: {row['timestamp']}, netherlands_timestamp: {row['netherlands_timestamp']}")

    except Exception as e:
        print(f"错误: {e}")
    finally:
        connection.close()

if __name__ == "__main__":
    main()